var co = require('../../resource/js/common.js')
var ws = require('../../resource/js/websocket.js')
var MAP = require('../../resource/js/map.js')
var pKeys = ['latitude', 'longitude']//position的keys
var app = getApp()
var _this, map   //地图参数  

Page({
    data: {
        p: app.Data.p,
        markers: [],
        ctrls: [],
        mapHeight: 0,
        addressBar: '',
        avatarUrl: '/resource/img/huaji.png',
        // 点击地图上店铺显示
        activeShop: false,
        shopID: '',
        // 扫码提示信息
        isHint: true,
        shopInfo: '',
        // 评分星星显示
        score: '',
        star: [],
        authConfirm: 0,
        isNewGuest: '',
        // 传递信息
        Biz_ID: '',
        Table_ID: ''
    },

    onLoad: function (opt) {
        _this = this
        //创建地图组件对象
        this.mapObj = wx.createMapContext('masterMap')
        //初始化地图：大小、masker控件
        this.initMap()
        //移到并获取地图中心
        this.moveAndGetMapCenter()
        // 获取附近店家
        this.getNearby()
        // 定时扫描提示的消息消失
        setTimeout(function () {
            _this.setData({ isHint: false })
        }, 8000)
        // this.ctrlEvent()
    },
    // 进入店铺
    intoShop: function (e) {
        var shopID = e.currentTarget.id
        console.log("【点击】===", shopID)
        if (shopID != '') {
            wx.navigateTo({
                url: '/02local/02shopHome/shopHome?Biz_ID=' + shopID,
            })
        }
    },
    //移到并获取地图中心
    moveAndGetMapCenter: function () {
        MAP.moveAndGetMapCenter(this.mapObj, function (res) {
            // console.log('【移到并获取地图中心】res', res)
            var loc = co.addValueForKey({}, res, pKeys)//只取经纬度
            app.Data.p = loc          //存app全局坐标
            _this.setData({//存本页数据
                p: loc
            })   
            _this.getLocationName(res)  //获取中文地址并显示
        })
    },
    //获取附近店家
    getNearby: function (loc) {
        var param = loc ? loc : this.data.p
        co.getShareApi('biz/Bmg/getNearbyListOnMap', param, function (res) {
            _this.setData({ markers: res.data })
        })
    },
    //调用坐标转中文地址
    getLocationName: function (loc) {
        MAP.getLocationName(loc, function (address) {
            _this.updateAddresBar(address)
        })
    },
    //更新地址栏信息
    updateAddresBar: function (address, mark) {
        // console.log("【获取更新数据】", mark)
        var url
        if (co.empty(mark)) {
            url = '/resource/img/huaji.png'
        } else {
            url = mark.avatarUrl
        }
        this.setData({
            addressBar: address.address,
            avatarUrl: url
        })
    },
    //初始化地图
    initMap: function () {
        var sys = wx.getSystemInfoSync()
        map = {
            width: sys.windowWidth,
            height: sys.windowHeight - 100,
            centerCtrlWidth: 40,
            centerCtrlHeight: 40,
        }
        map.centerCtrlLeft = (map.width - map.centerCtrlWidth) / 2
        map.centerCtrlTop = map.height / 2 - map.centerCtrlHeight

        this.setData({
            mapHeight: map.height,
            ctrls: this.initCtrls(map)
        })
    },
    //点击地图商家标签
    markerTap: function (e) {
        var mark = this.data.markers[e.markerId]
        MAP.getLocationName(co.getLoc(mark), function (address) {
            // 更新顶部信息
            _this.updateAddresBar(address, mark)
            _this.setData({
                activeShop: true,
                shopID: mark.Biz_ID
            })
            // 显示评分信息
            _this.showStart(mark.Score)
        })
    },
    // 评分显示星星
    showStart(Score) {
        const LENGTH = 5;
        const CLS_ON = "../../resource/icon/star/on.png"
        const CLS_OFF = "../../resource/icon/star/off.png"
        const CLS_HALF = "../../resource/icon/star/half.png"
        //评分判断
        let starArray = []
        //lpData.data.comment.sRate表示获取当前评分，例如：4.65等
        let score = Math.floor(Score * 2) / 2
        let hasDecimal = score % 1 !== 0
        let integer = Math.floor(score)
        for (let i = 0; i < integer; i++) {
            starArray.push(CLS_ON)
        }
        if (hasDecimal) {
            starArray.push(CLS_HALF)
        }
        while (starArray.length < LENGTH) {
            starArray.push(CLS_OFF)
        }
        //存入星星数组
        _this.setData({
            score: Score,
            star: starArray
        })
    },
    //获取地图中心及重新获取附近店家
    getMapCenterAndNearbyMarkers: function () {
        MAP.getMapCenterAddress(this.mapObj, function (loc) {
            _this.getNearby(loc)//重新获取附近的店家
            _this.getLocationName(loc)
        })
    },
    //点击控件事件
    ctrlEvent: function (e) {
        var e_id = e.controlId
        if (e_id == 'toUserLoc') {    //返回用户位置中心
            this.moveAndGetMapCenter()
            this.setData({
                activeShop: false,
                shopID: ''
            })
        }
    },
    //初始化地图控件
    initCtrls: function (map) {
        //间距，回原点图宽，呼叫按钮宽高
        var space = 15, to_w = 40, to_q = 29
        return [
            {
                id: 'centerMark',
                iconPath: '/resource/img/selected.png',
                position: {
                    left: map.centerCtrlLeft,
                    top: map.centerCtrlTop,
                    width: map.centerCtrlWidth,
                    height: map.centerCtrlHeight
                },
            },
            {
                id: 'toUserLoc',
                iconPath: '/resource/img/gps.png',
                position: {
                    left: space,
                    top: map.height - 80,
                    width: to_w,
                    height: to_w,
                },
                clickable: true
            }
        ]
    },
    // 扫描点菜
    scanCode: function () {
        wx.scanCode({
            onlyFromCamera: true,
            success: function (res) {
                var str = res.result
                if (str.indexOf('meal.52g3.cc/index/index/index') > -1) {
                    var strArr = str.split('/')
                    // console.log("【获取】===", strArr, strArr[9], strArr[7])
                    _this.getTableInfo(strArr[9], strArr[7])
                    _this.setData({
                        Biz_ID: strArr[9],
                        Table_ID: strArr[7]
                    })
                } else {
                    co.toast('您扫的不是码上点的二维码')
                }
            }
        })
    },
    //获取桌号对应订单信息
    getTableInfo: function (biz_id, tableId) {
        var param = {
            Biz_ID: biz_id,
            Table_ID: tableId
        }
        co.getShareApi('order/Omg/tableOrder', param, function (res) {
            console.log("【获取返回信息】===", res.data)
            if (res.code == 0) {//此桌有订单时
                var obj = JSON.stringify(res.data)
                wx.navigateTo({
                    url: '/02local/07tableOrder/tableOrder?obj='+obj,
                })
            } else if (res.code == 29353) {//此桌无订单时
                wx.navigateTo({
                    url: '/02local/03foodInfo/foodInfo?Biz_ID=' + _this.data.Biz_ID + '&Table_ID=' + _this.data.Table_ID
                })
            }
        })
    }
})